import { mapState, mapGetters, createNamespacedHelpers, useStore } from 'vuex'
import { computed } from 'vue'

export function useState(moduleName, mapper) {
  return useType(mapState, 'mapState', mapper, moduleName)
}

export function useGetters(moduleName, mapper) {
  return useType(mapGetters, 'mapGetters', mapper, moduleName)
}

function useType(mapType, mapName, mapper, moduleName) {
  let mapModuleType = mapType

  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapModuleType = createNamespacedHelpers(moduleName)[mapName]
  } else {
    mapper = moduleName
  }

  return useMapper(mapper, mapModuleType)
}

function useMapper(mapper, mapModuletype) {
  const store = useStore()

  const storeState = mapModuletype(mapper)

  const state = {}

  Object.keys(storeState).forEach(fnkey => {
    state[fnkey] = computed(storeState[fnkey].bind({ $store: store }))
  })
  return state
}